lower_word='abcdefghijklmnopqrstuvwxyz'
upper_word='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#求逆
def inv(a_ind):
    m=[1,0,26]
    n=[0,1,a_ind]
    s=[0,0,0]
    while n[-1] != 1:
        for i in range(3):
            x=m[-1]//n[-1]
            s[i]=m[i]-x*n[i]
        m=n
        n=s
    t=n[1]%26
    return t
def is_valid_a(a,b):
    if a in lower_word:
        a_ind = lower_word.index(a)
    elif a in upper_word:
        a_ind = upper_word.index(a)
    if b in lower_word:
        b_ind = lower_word.index(b)
    elif b in upper_word:
        b_ind = upper_word.index(b)
    if a_ind % 2 == 1 and a_ind != 13 :
        if a_ind == 1 and b_ind == 0 :
                return False\
        
        else:
                return True
        return  True
    else:
            return False
def encrypt_s(p,a,b):
    if is_valid_a(a,b):
        if a in lower_word:
            a_ind = lower_word.index(a)
        elif a in upper_word:
            a_ind = upper_word.index(a)
        else:
            return False
        if b in lower_word:
            b_ind = lower_word.index(b)
        elif b in upper_word:
            b_ind = upper_word.index(b)
        else:
            return False
        t = ' '
        for i in p:
            if i in lower_word:
                    t += lower_word[(lower_word.index(i) * a_ind + b_ind) % 26]
            elif i in upper_word:
                t += upper_word[(upper_word.index(i) * a_ind + b_ind) % 26]
                pass
            else:
                t += i
        return t
    else:
        return None

def decrypt_s(c,a,b):
    if is_valid_a(a,b):
        if a in lower_word:
            a_ind = lower_word.index(a)
        elif a in upper_word:
            a_ind = upper_word.index(a)
        else:
            return False
        if b in lower_word:
            b_ind = lower_word.index(b)
        elif b in upper_word:
            b_ind = upper_word.index(b)
        else:
            return False
        a_inv=inv(a_ind)
        t = ' '
        for i in c:
            if i in lower_word:
                t += lower_word[((lower_word.index(i) - b_ind)*a_inv) % 26]
            elif i in upper_word:
                t += upper_word[((upper_word.index(i) - b_ind)*a_inv) % 26]
                pass
            else:
                t += i
        return t
    else:
        return None

if __name__ == "__main__":
    p = "Hello,World"
    a = 'd'
    b = 'f'
    c = encrypt_s(p,a,b)
    print(c)
    print(decrypt_s(c,a,b))